package com.cuitrip.business.tripservice.presenter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.TrackBusiness;
import com.cuitrip.business.home.favorite.FavoriteListFragment;
import com.cuitrip.business.home.favorite.TravelTrip;
import com.cuitrip.business.home.favorite.proxy.FavProxy;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.proxy.LoginProxy;
import com.cuitrip.business.order.OrderCreateActivity;
import com.cuitrip.business.share.model.ServiceShareObject;
import com.cuitrip.business.track.TrackProxy;
import com.cuitrip.business.tripservice.ServiceDetailActivity;
import com.cuitrip.business.tripservice.TripEditActivity;
import com.cuitrip.business.tripservice.TripOtherInstructionActivity;
import com.cuitrip.business.tripservice.model.ServiceDetail;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.ui.TripDetailView;
import com.cuitrip.business.user.BookingCompleteUserInfoActivity;
import com.cuitrip.business.user.PersonActivity;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.webview.H5UrlMaker;
import com.cuitrip.business.webview.proxy.WebViewProxy;
import com.cuitrip.util.I118Util;
import com.cuitrip.util.track.TrackUtil;
import com.lab.mvp.presenter.Presenter;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.ArrayUtil;
import com.lab.utils.MessageUtils;


/**
 * 行程详情页面presenter
 * Created by ak on 16/2/4.
 */
public class TripDetailPresenter implements Presenter<TripDetailView>, IProxyCallback {

    TripDetailView mTripDetailView;

    private String id;

    private ServiceDetail mServiceDetail;

    private ApiProxy mApiProxy = new ApiProxy(this);

    private int mode;

    private int checkStatus;
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (FavoriteListFragment.FAV_CHANGED_ACTION.equals(intent.getAction())) {
                if (intent.hasExtra(TravelTrip.KEY_TRAVEL_TRIP_ID)) {
                    String sid = intent.getStringExtra(TravelTrip.KEY_TRAVEL_TRIP_ID);
                    boolean value = intent.getBooleanExtra(FavoriteListFragment.FAV_CHANGED_VALUE_KEY, false);
                    if (mServiceDetail != null && sid.equals(mServiceDetail.getServiceInfo().getSid())) {
                        updateFavValue(value);
                    }
                }
            }
        }
    };

    public void loadServiceDetail(String id, int checkStatus, int mode) {
        mTripDetailView.displayLoading();
        this.checkStatus = checkStatus;
        this.mode = mode;
        this.id = id;
        if (mode == ServiceDetailActivity.SNAPSHOT) {
            ServiceBusiness.getServiceSnapShot(mApiProxy, id);
        } else {
            ServiceBusiness.getServiceDetail(mApiProxy, id, checkStatus == ServiceInfo.STATUS_DRAFT ? 1 : 0);
        }
    }

    @Override
    public void attachView(TripDetailView view) {
        mTripDetailView = view;
        IntentFilter filter = new IntentFilter(FavoriteListFragment.FAV_CHANGED_ACTION);
        mTripDetailView.getContext().registerReceiver(mReceiver, filter);
    }

    @Override
    public void detachView() {
        this.mTripDetailView.getContext().unregisterReceiver(mReceiver);
        this.mTripDetailView = null;
    }

    private void handResponse(CtApiResponse response) {
        if (mTripDetailView == null) {
            return;
        }
        if (response.isResponseNormal()) {
            if (response.result instanceof ServiceDetail) {
                mServiceDetail = (ServiceDetail) response.result;
                mTripDetailView.displayContent();
                renderUi(mServiceDetail);
            } else if (response.result instanceof CtUserInfo) {
                CtUserInfo userInfo = (CtUserInfo) response.result;
                if (userInfo.isFinished()) {
                    navigateOrderPage();
                } else {
                    navigateCompleteUserInfoPage(userInfo);
                }

            } else {
                mTripDetailView.displayNoNetwork();
                if (!TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
            }
        }
    }

    public void judgeBasicUserInfo() {
        OrderBusiness.checkBasicUserInfo(mApiProxy);
    }

    private void renderUi(ServiceDetail serviceDetail) {
        int reviewCount;
        if (serviceDetail.getReviewInfo() == null) {
            reviewCount = 0;
        } else {
            reviewCount = Integer.valueOf(serviceDetail.getReviewInfo().getReviewNum());
        }
        mTripDetailView.showRightText();
        mTripDetailView.renderServicePartInfo(serviceDetail.getServiceInfo(), reviewCount);
        mTripDetailView.renderInsiderInfo(serviceDetail.getUserInfo());
        mTripDetailView.renderCommentInfo(serviceDetail.getReviewInfo());
        mTripDetailView.renderFavInfo(serviceDetail.getFavInfo());
        mTripDetailView.renderFavValue(serviceDetail.isFav(), false);
    }

    private void updateFavValue(boolean isFav) {
        mServiceDetail.setIsLike(isFav ? 1 : 0);
        mTripDetailView.renderFavValue(isFav, true);
    }

    public void toggleFavoriteService() {
        if (!LoginInstance.isLogin()) {
            LoginProxy.getInstance().gotoUserEnter(mTripDetailView.getContext());
            return;
        }
        if (mServiceDetail.isFav()) {
            updateFavValue(false);
            FavProxy.getInstance().unFavTrip(mServiceDetail.getServiceInfo().getSid(), new FavProxy.Callback() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onFail(String message) {
                    updateFavValue(true);
                    MessageUtils.showToast(message);
                }
            });
            TrackProxy.getInstance().operationAction(TrackBusiness.Source.SERVICE_DETAIL, TrackBusiness.Action.DISLIKE, "", "", null);
        } else {
            updateFavValue(true);
            ServiceInfo item = mServiceDetail.getServiceInfo();
            FavProxy.getInstance().favTrip(item.getSid(), item.getName(), item.getAddress(), item.getBackPic(),
                    item.getInsiderId(), mServiceDetail.getUserInfo().getNick(), mServiceDetail.getUserInfo().getHeadPic(), mServiceDetail.getUserInfo().getCareer(), new FavProxy.Callback() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onFail(String message) {
                            updateFavValue(false);
                            MessageUtils.showToast(message);
                        }
                    });
            TrackProxy.getInstance().operationAction(TrackBusiness.Source.SERVICE_DETAIL, TrackBusiness.Action.ADDLIKE, "", "", null);
        }
    }

    public void navigateInsiderPage() {
        PersonActivity.jumpPersonActivity(mTripDetailView.getContext(), mServiceDetail.getUserInfo().getNick(), mServiceDetail.getServiceInfo().getInsiderId());
    }

    public void navigateOtherNotes() {
        TripOtherInstructionActivity.startOtherInstructionLayout(mTripDetailView.getContext(), mServiceDetail.getServiceInfo().otherNotes, false);
    }

    public void navigateDescriptionPage() {
        ServiceInfo serviceInfo = mServiceDetail.getServiceInfo();
        TrackUtil.trackScreenName("/service/description");
        if (!TextUtils.isEmpty(serviceInfo.getSid())) {
            JSONObject jsonObject = new JSONObject();
            if (mode == ServiceDetailActivity.SNAPSHOT) {
                jsonObject.put("orderId", id);
                jsonObject.put("lang", I118Util.getLanguageTag());
                CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                if (userInfo != null) {
                    jsonObject.put("token", userInfo.getToken());
                    jsonObject.put("uid", userInfo.getUid());
                }
                WebViewProxy.getInstance().browseWeb(mTripDetailView.getContext(), H5UrlMaker.getTripSnapShotDesc(), jsonObject);
            } else {
                jsonObject.put("sid", serviceInfo.getSid());
                jsonObject.put("isDraft", checkStatus == ServiceInfo.STATUS_DRAFT ? 1 : 0);
                WebViewProxy.getInstance().browseWeb(mTripDetailView.getContext(), H5UrlMaker.getTripDesc(), jsonObject);
            }

        }
    }

    public void navigateOrderPage() {
        OrderCreateActivity.start(mTripDetailView.getContext(), mServiceDetail.getServiceInfo());
    }

    public void navigateCompleteUserInfoPage(CtUserInfo userInfo) {
        BookingCompleteUserInfoActivity.startActivity(mTripDetailView.getContext(), mServiceDetail.getServiceInfo(), userInfo);
    }

    public void navigateEditPage() {
        TripEditActivity.navigate2TripEditActivity(mTripDetailView.getContext(), mServiceDetail.getServiceInfo(), true);
    }

    public void navigateSharePage() {
        if (mServiceDetail == null || ArrayUtil.isNullOrEmpty(mServiceDetail.getServiceInfo().getPic())) {
            return;
        }
        mTripDetailView.showShare(ServiceShareObject.getInstance(mServiceDetail.getServiceInfo().getSid(), mServiceDetail.getServiceInfo().getName(), mServiceDetail.getServiceInfo().getBackPic(), mServiceDetail.getServiceInfo().getDescptWithnoPic()));

    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        handResponse(response);
        return false;
    }
}
